package com.dragon.modules.yuegou.web;

import javax.servlet.http.HttpServletRequest;

/**
 * Web工具类
 * 
 * @author liuwu
 *
 */
public class WebUtils {

	private static final String UNKNOWN = "unknown";
	/**
	 * 获取真实的客户端IP <br>
	 * 兼容经过代理的情况
	 * 
	 * @param request HTTP请求
	 * @return 客户端IP
	 */
	public static String getRealClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return getOriginalIp(ip);
	}

	private static String getOriginalIp(String ipList) {
		if (ipList != null && ipList.contains(",")) {
			String[] ips = ipList.split(",");
			for (String ip : ips) {
				if (!(UNKNOWN.equalsIgnoreCase(ip))) {
					return ip;
				}
			}
		}
		return ipList;
	}

}
